package aar.test.tessocr;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import org.opencv.android.OpenCVLoader;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.adapter.CompanySearchInfoAdapter;
import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.CompanySearchModel;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.tessOcrUtil.CameraView2;
import aar.test.tessocr.tessOcrUtil.ListViewForScrollView;
import aar.test.tessocr.tessOcrUtil.RecycledImageView;
import aar.test.tessocr.tessOcrUtil.TesseractUtil;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.LogUtils;
import aar.test.tessocr.utils.TipHelper;
import aar.test.tessocr.utils.UnzipAssets;
import aar.test.tessocr.utils.Urls;
import clx.tessocr.ocreng.R;
import lib_zxing.activity.CaptureActivity;
import lib_zxing.activity.CaptureFragment;
import lib_zxing.activity.CodeUtils;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.LoginActivity.JSON;

public class ObtainModeActivity extends BaseActivity {

    private Context mContext;

    private DisplayMetrics dm;

    private LinearLayout company_scan, company_write;

    private EditText com_edit, company_info_datetime, company_info_num, company_info_save;

    private EditText company_info_datetime1, company_info_datetime2, company_info_datetime3, company_info_datetime4, company_info_datetime5;
    private EditText company_info_num1, company_info_num2, company_info_num3, company_info_num4, company_info_num5;
    private EditText company_info_save1, company_info_save2, company_info_save3, company_info_save4, company_info_save5;

//    private CameraView2 com_camera;

    private LinearLayout left_layout;

    private TextView title_info;


    private Button cab_open;

    private ListViewForScrollView mListView;

    private TextView mTextView, title_company_name, title_company_contact, title_company_phone, title_company_tip;

    private PopupWindow comSearchPopupWindow;

    private View contentView;

    private CompanySearchModel mCompanySearchModel;

//    private RecycledImageView mImageView,main_image2,main_image3,main_image4,main_image5,main_image6,main_image7;


//    private TextView cal_text,show_text;

    private String text;

    private Spinner company_info_spin, company_info_spin1, company_info_spin2, company_info_spin3, company_info_spin4, company_info_spin5;

    private ArrayAdapter<String> arrayAdapter, arrayAdapter1, arrayAdapter2, arrayAdapter3, arrayAdapter4, arrayAdapter5;

    private ImageView company_info_add, company_info_add1, company_info_add2, company_info_add3, company_info_add4, company_info_add5;

    private RelativeLayout add_layout,add_layout1, add_layout2, add_layout3, add_layout4, add_layout5;

    private int index,index1,index2,index3,index4,index5;

    private RelativeLayout  com_edit_layout;
    private FrameLayout fl_zxing_container;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_obtain_mode);
        initView();

        dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        iniLoadOpenCV();

        if (Build.VERSION.SDK_INT >= 23) {
            requestP();

        } else {

            unZipAssset();
        }


    }


    private void initView() {

        CaptureFragment captureFragment = new CaptureFragment();
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_zxing_container, captureFragment).commit();
        captureFragment.setCameraInitCallBack(new CaptureFragment.CameraInitCallBack() {
            @Override
            public void callBack(Exception e) {
                if (e == null) {

                } else {
                    Log.e("TAG", "callBack: ", e);
                }
            }
        });


        com_edit_layout = findViewById(R.id.com_edit_layout);

        fl_zxing_container = findViewById(R.id.fl_zxing_container);




        company_info_spin = findViewById(R.id.company_info_spin);
        company_info_spin1 = findViewById(R.id.company_info_spin1);
        company_info_spin2 = findViewById(R.id.company_info_spin2);
        company_info_spin3 = findViewById(R.id.company_info_spin3);
        company_info_spin4 = findViewById(R.id.company_info_spin4);
        company_info_spin5 = findViewById(R.id.company_info_spin5);

        String[] ass = getResources().getStringArray(R.array.a_z_);

        arrayAdapter = new ArrayAdapter<String>(this, R.layout.letter_select_item, ass);
        arrayAdapter.setDropDownViewResource(R.layout.letter_select_item);
        company_info_spin.setAdapter(arrayAdapter);
        company_info_spin.setSelection(0);
        company_info_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                company_info_spin.setSelection(i);
                index=i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        arrayAdapter1 = new ArrayAdapter<String>(this, R.layout.letter_select_item, ass);
        arrayAdapter1.setDropDownViewResource(R.layout.letter_select_item);
        company_info_spin1.setAdapter(arrayAdapter1);
        company_info_spin1.setSelection(0);
        company_info_spin1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                company_info_spin1.setSelection(i);
                index1=i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.letter_select_item, ass);
        arrayAdapter2.setDropDownViewResource(R.layout.letter_select_item);
        company_info_spin2.setAdapter(arrayAdapter2);
        company_info_spin2.setSelection(0);
        company_info_spin2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                company_info_spin2.setSelection(i);
                index2=i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        arrayAdapter3 = new ArrayAdapter<String>(this, R.layout.letter_select_item, ass);
        arrayAdapter3.setDropDownViewResource(R.layout.letter_select_item);
        company_info_spin3.setAdapter(arrayAdapter3);
        company_info_spin3.setSelection(0);
        company_info_spin3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                company_info_spin3.setSelection(i);
                index3=i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        arrayAdapter4 = new ArrayAdapter<String>(this, R.layout.letter_select_item, ass);
        arrayAdapter4.setDropDownViewResource(R.layout.letter_select_item);
        company_info_spin4.setAdapter(arrayAdapter4);
        company_info_spin4.setSelection(0);
        company_info_spin4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                company_info_spin4.setSelection(i);
                index4=i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        arrayAdapter5 = new ArrayAdapter<String>(this, R.layout.letter_select_item, ass);
        arrayAdapter5.setDropDownViewResource(R.layout.letter_select_item);
        company_info_spin5.setAdapter(arrayAdapter5);
        company_info_spin5.setSelection(0);
        company_info_spin5.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                company_info_spin5.setSelection(i);
                index5=i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        String ye = year + "";
        ye = ye.substring(2, 4);

        company_info_datetime = findViewById(R.id.company_info_datetime);
        company_info_datetime.setText(ye);

        company_info_datetime1 = findViewById(R.id.company_info_datetime1);
        company_info_datetime1.setText(ye);
        company_info_datetime2 = findViewById(R.id.company_info_datetime2);
        company_info_datetime2.setText(ye);
        company_info_datetime3 = findViewById(R.id.company_info_datetime3);
        company_info_datetime3.setText(ye);
        company_info_datetime4 = findViewById(R.id.company_info_datetime4);
        company_info_datetime4.setText(ye);
        company_info_datetime5 = findViewById(R.id.company_info_datetime5);
        company_info_datetime5.setText(ye);


        company_info_num = findViewById(R.id.company_info_num);
        company_info_num1 = findViewById(R.id.company_info_num1);
        company_info_num2 = findViewById(R.id.company_info_num2);
        company_info_num3 = findViewById(R.id.company_info_num3);
        company_info_num4 = findViewById(R.id.company_info_num4);
        company_info_num5 = findViewById(R.id.company_info_num5);


        company_info_save = findViewById(R.id.company_info_save);
        company_info_save1 = findViewById(R.id.company_info_save1);
        company_info_save2 = findViewById(R.id.company_info_save2);
        company_info_save3 = findViewById(R.id.company_info_save3);
        company_info_save4 = findViewById(R.id.company_info_save4);
        company_info_save5 = findViewById(R.id.company_info_save5);


        title_company_name = findViewById(R.id.title_company_name);
        title_company_contact = findViewById(R.id.title_company_contact);
        title_company_phone = findViewById(R.id.title_company_phone);
        title_company_tip = findViewById(R.id.title_company_tip);


//        middle_line = findViewById(R.id.middle_line);
//        res_text = findViewById(R.id.res_text);

        cab_open = findViewById(R.id.cab_open);
        cab_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (null != com_camera) {
//                    com_camera.isScanning = false;
//                }

                openExpressGrid();

            }
        });

//        mImageView=findViewById(R.id.main_image);

        title_info = findViewById(R.id.title_info);


        left_layout = findViewById(R.id.left_layout);
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        com_edit = findViewById(R.id.com_edit);

//        com_camera = findViewById(R.id.com_camera);

//        int juli = (int) (98 * getResources().getDisplayMetrics().density);
//
//        LogUtils.e("MainActivity", "sPathVid.getStatusBarHeight()==" + getStatusBarHeight());
//        LogUtils.e("MainActivity", "sPathVid.getStatusBarHeight()1111==" + (juli + 85));
//        com_camera.settt(juli);


        company_scan = findViewById(R.id.company_scan);
        company_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (null != com_camera) {
//                    com_camera.isScanning = false;
//                }
//                com_edit.setVisibility(View.GONE);
//                mTextView.setVisibility(View.GONE);
                com_edit_layout.setVisibility(View.GONE);
                        fl_zxing_container.setVisibility(View.VISIBLE);
//                com_camera.setVisibility(View.VISIBLE);
                title_info.setText("显示扫描信息");
//                middle_line.setVisibility(View.VISIBLE);
//                res_text.setVisibility(View.VISIBLE);
//                mImageView.setVisibility(View.VISIBLE);

                title_company_name.setText("公司名称");
                title_company_phone.setText("公司联系人");
                title_company_contact.setText("联系人电话");
                title_company_tip.setText("");
                company_info_num.setText("");
                company_info_num1.setText("");
                company_info_num2.setText("");
                company_info_num3.setText("");
                company_info_num4.setText("");
                company_info_num5.setText("");
                company_info_save.setText("");
                company_info_save1.setText("");
                company_info_save2.setText("");
                company_info_save3.setText("");
                company_info_save4.setText("");
                company_info_save5.setText("");

            }
        });

        company_write = findViewById(R.id.company_write);
        company_write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                com_edit.setVisibility(View.VISIBLE);
//                mTextView.setVisibility(View.VISIBLE);

                com_edit_layout.setVisibility(View.VISIBLE);
                fl_zxing_container.setVisibility(View.GONE);
//                com_camera.setVisibility(View.GONE);
                title_info.setText("显示输入信息");
//                middle_line.setVisibility(View.GONE);
//                res_text.setVisibility(View.GONE);
//                mImageView.setVisibility(View.GONE);

                title_company_name.setText("公司名称");
                title_company_phone.setText("公司联系人");
                title_company_contact.setText("联系人电话");
                title_company_tip.setText("");
                company_info_num.setText("");
                company_info_num1.setText("");
                company_info_num2.setText("");
                company_info_num3.setText("");
                company_info_num4.setText("");
                company_info_num5.setText("");
                company_info_save.setText("");
                company_info_save1.setText("");
                company_info_save2.setText("");
                company_info_save3.setText("");
                company_info_save4.setText("");
                company_info_save5.setText("");
            }
        });


        mTextView = (TextView) findViewById(R.id.textview);
        mTextView.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                //如果输入框内容为空，提示请输入搜索内容

                if (TextUtils.isEmpty(com_edit.getText().toString().trim())) {
                    Toast.makeText(mContext, "请输入需要查询的公司", Toast.LENGTH_LONG).show();
                } else {
                    //判断cursor是否为空
//                    if (cursor != null) {
//                        int columnCount = cursor.getCount();
//                        if (columnCount == 0) {
//                            Toast.makeText(context,"对不起，没有你要搜索的内容",Toast.LENGTH_LONG).show();
//                        }
//                    }


                    companySearch(com_edit.getText().toString().trim());
                }

            }
        });


        contentView = LayoutInflater.from(ObtainModeActivity.this).inflate(R.layout.popwindow_layout, null);
        mListView = contentView.findViewById(R.id.listview);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (comSearchPopupWindow != null && comSearchPopupWindow.isShowing()) {
                    comSearchPopupWindow.dismiss();
                }

                if (null != mList && mList.size() > 0 && null != mList.get(i)) {

                    title_company_name.setText(mList.get(i).getCompanyname());
                    title_company_phone.setText(mList.get(i).getContact());
                    title_company_contact.setText(mList.get(i).getContactname());
                    String mm = getResources().getString(R.string.tip_header) + mList.get(i).getCompanyname() + getResources().getString(R.string.tip_hcontext);
                    title_company_tip.setText(mm);
                    company_info_num.setText(mList.get(i).getCompanynum());
                    company_info_num1.setText(mList.get(i).getCompanynum());
                    company_info_num2.setText(mList.get(i).getCompanynum());
                    company_info_num3.setText(mList.get(i).getCompanynum());
                    company_info_num4.setText(mList.get(i).getCompanynum());
                    company_info_num5.setText(mList.get(i).getCompanynum());
                }

                mCompanySearchModel = new CompanySearchModel();
                mCompanySearchModel = mList.get(i);


            }
        });
        comSearchPopupWindow = new PopupWindow(contentView,
                GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT, true);
        //ICOM-4096 begin add by b.jiang 20170112
        comSearchPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        comSearchPopupWindow.setFocusable(true);
        comSearchPopupWindow.setOutsideTouchable(true);

//        show_text= findViewById(R.id.show_text);
//        cal_text= findViewById(R.id.cal_text);
//        res_text.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                if (null != com_camera) {
////                    com_camera.isScanning = false;
////                }
//
//                if (null != title_company_name) {
//                    title_company_name.setText("");
//                }
//
//            }
//        });


//        mImageView =  findViewById(R.id.main_image);
//        main_image2 =  findViewById(R.id.main_image2);
//        main_image3 =  findViewById(R.id.main_image3);
//        main_image4 =  findViewById(R.id.main_image4);
//        main_image5 =  findViewById(R.id.main_image5);
//        main_image6 =  findViewById(R.id.main_image6);
//        main_image7 =  findViewById(R.id.main_image7);

//        com_camera.setTag(mImageView);
//        com_camera.setShowImage(main_image2);
//        com_camera.setShowImage3(main_image3);
//        com_camera.setShowImage4(main_image4);
//        com_camera.setShowImage5(main_image5);
//        com_camera.setShowImage6(main_image6);
//        com_camera.setShowImage7(main_image7);

//        com_camera.setShowTextListener(new CameraView2.showTextListener() {
//            @Override
//            public void getRecBitmap(final Bitmap bap) {
//
//
//            }
//
//            @Override
//            public void showText(String tt) {
//
//                text = tt;
//                TipHelper.Vibrate(ObtainModeActivity.this, 1000);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////
//                        if (!TextUtils.isEmpty(text)) {
//                            title_company_name.setText(text);
//
//                        }
//
//                    }
//                });
//
//            }
//        });


        add_layout = findViewById(R.id.add_layout);
        add_layout1 = findViewById(R.id.add_layout1);
        add_layout2 = findViewById(R.id.add_layout2);
        add_layout3 = findViewById(R.id.add_layout3);
        add_layout4 = findViewById(R.id.add_layout4);
        add_layout5 = findViewById(R.id.add_layout5);


        company_info_add = findViewById(R.id.company_info_add);
        company_info_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add_layout1.setVisibility(View.VISIBLE);
            }
        });
        company_info_add1 = findViewById(R.id.company_info_add1);
        company_info_add1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add_layout2.setVisibility(View.VISIBLE);
            }
        });
        company_info_add2 = findViewById(R.id.company_info_add2);
        company_info_add2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add_layout3.setVisibility(View.VISIBLE);
            }
        });
        company_info_add3 = findViewById(R.id.company_info_add3);
        company_info_add3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add_layout4.setVisibility(View.VISIBLE);
            }
        });
        company_info_add4 = findViewById(R.id.company_info_add4);
        company_info_add4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add_layout5.setVisibility(View.VISIBLE);
            }
        });
        company_info_add5 = findViewById(R.id.company_info_add5);


    }


    private void iniLoadOpenCV() {
        boolean success = OpenCVLoader.initDebug();
        if (success) {
            Log.e("MainActivity", "OpenCV Library loaded...");
        } else {
            Toast.makeText(this.getApplicationContext(), "could not load opencv lib...", Toast.LENGTH_LONG).show();
        }
    }


    private void requestP() {

        AndPermission.with(this)
                .requestCode(ConstantPara.REQUEST_CODE_PERMISSION_SD)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).
                                show();
                    }
                })
                .start();
    }


    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(MainActivity.this, "111111111111", Toast.LENGTH_SHORT).show();
                    unZipAssset();
                    break;
                }

            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case ConstantPara.REQUEST_CODE_PERMISSION_SD: {
//                    Toast.makeText(ShowMobleSDMediaActivity.this, R.string.message_post_failed, Toast.LENGTH_SHORT).show();
                    break;
                }

            }


            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(ObtainModeActivity.this, deniedPermissions)) {

                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(ObtainModeActivity.this, ConstantPara.REQUEST_CODE_SETTING, dm).show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

            }
        }
    };


    private void unZipAssset() {

        prepareSdPath();

        prepareSdPath2();

        try {

            File file = new File(TesseractUtil.TESSBASE_PATH_DOWN);

            File file2 = new File(TesseractUtil.TESSBASE_PATH_DOWN + "/normal.traineddata");

            if (!file.exists() || (file.exists() && !file2.exists())) {
                new Thread() {
                    public void run() {
                        //在新线程中以同名覆盖方式解压
                        UnzipAssets.unZip(ObtainModeActivity.this, ConstantPara.UN_ZIP_ASSET_NAME, TesseractUtil.TESSBASE_PATH, true);
                    }
                }.start();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath() {

        try {

            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRootThumbnail = new File(TesseractUtil.TESSBASE_PATH);
                if (!sPathRootThumbnail.exists()) {
                    sPathRootThumbnail.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    //准备sd卡存储路径用来存储视频和图片
    private void prepareSdPath2() {

        String RootFilePath = Environment.getExternalStorageDirectory() + "/DCIM/";

        String sSubDir = "normal";
//        String RootFilePath=  Environment.getExternalStorageDirectory() + "/Download/";

        try {


            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File sPathRoot = new File(RootFilePath);
                if (!sPathRoot.exists()) {
                    sPathRoot.mkdirs();
                }
                File sPathVid = new File(RootFilePath + sSubDir);
                LogUtils.e("MainActivity", "sPathVid.exists()==" + sPathVid.exists());
                if (!sPathVid.exists()) {
                    sPathVid.mkdirs();
                }

            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public int getStatusBarHeight() {
        int result1 = 0;
        LogUtils.e("getStatusBarHeight", "result1.result1()==" + result1);
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result1 = getResources().getDimensionPixelSize(resourceId);
        }

        LogUtils.e("getStatusBarHeight", "result1.result1()==" + result1);
        return result1;
    }


    private List<CompanySearchModel> mList;

    private void companySearch(final String searchInfo) {

        Map<String, Object> map = new HashMap<>();
        map.put("keyword", searchInfo);

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<CompanySearchModel>>>post(Urls.URL_COMPANYSEARCH)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<CompanySearchModel>>>(ObtainModeActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<CompanySearchModel>>> response) {


                        Log.e("MainActivity", "onSuccess-----logout---------------" + response.body().data);


                        if (null != response.body().data && response.body().data.size() > 0) {
                            mList = new ArrayList<>();
                            mList = response.body().data;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    comSearchPopupWindow.showAsDropDown(com_edit);
                                    mListView.setVisibility(View.VISIBLE);
                                    CompanySearchInfoAdapter adapter = new CompanySearchInfoAdapter(mContext, mList, searchInfo);
                                    mListView.setAdapter(adapter);


                                }
                            });
                        } else {


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mListView.setVisibility(View.GONE);
                                }
                            });

                            if (comSearchPopupWindow != null && comSearchPopupWindow.isShowing()) {
                                comSearchPopupWindow.dismiss();
                            }

                        }


                    }

                    @Override
                    public void onError(Response<LzyResponse<List<CompanySearchModel>>> response) {
                        Log.e("MainActivity", "onError---------------------");
                        if (comSearchPopupWindow != null && comSearchPopupWindow.isShowing()) {
                            comSearchPopupWindow.dismiss();
                        }
                    }
                });


    }


    private void companySearchID(final String searchInfo) {

        Map<String, Object> map = new HashMap<>();
        map.put("companyId", searchInfo);

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<CompanySearchModel>>>post(Urls.URL_COMPANYSEARCH)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<CompanySearchModel>>>(ObtainModeActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<CompanySearchModel>>> response) {


                        Log.e("MainActivity", "onSuccess-----logout---------------" + response.body().data);


                        if (null != response.body().data && response.body().data.size() > 0) {
                            mList = new ArrayList<>();
                            mList = response.body().data;
                            mCompanySearchModel=new CompanySearchModel();
                            mCompanySearchModel =mList.get(0);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (null != mList && mList.size() > 0) {

                                        title_company_name.setText(mList.get(0).getCompanyname());
                                        title_company_phone.setText(mList.get(0).getContact());
                                        title_company_contact.setText(mList.get(0).getContactname());
                                        String mm = getResources().getString(R.string.tip_header) + mList.get(0).getCompanyname() + getResources().getString(R.string.tip_hcontext);
                                        title_company_tip.setText(mm);
                                        company_info_num.setText(mList.get(0).getCompanynum());
                                        company_info_num1.setText(mList.get(0).getCompanynum());
                                        company_info_num2.setText(mList.get(0).getCompanynum());
                                        company_info_num3.setText(mList.get(0).getCompanynum());
                                        company_info_num4.setText(mList.get(0).getCompanynum());
                                        company_info_num5.setText(mList.get(0).getCompanynum());


                                    }



                                }
                            });
                        } else {

                        }


                    }

                    @Override
                    public void onError(Response<LzyResponse<List<CompanySearchModel>>> response) {
                        Log.e("MainActivity", "onError---------------------");

                    }
                });


    }




    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (comSearchPopupWindow != null && comSearchPopupWindow.isShowing()) {
            comSearchPopupWindow.dismiss();
        }

        OkGo.getInstance().cancelTag(this);
    }


    private String numberSum="";
    private String numberSum1="";
    private String numberSum2="";
    private String numberSum3="";
    private String numberSum4="";
    private String numberSum5="";

    private void openExpressGrid() {
        numberSum="";
        numberSum1="";
        numberSum2="";
        numberSum3="";
        numberSum4="";
        numberSum5="";
        if (null == mCompanySearchModel) {
            Toast.makeText(ObtainModeActivity.this, "请输入需要查询的公司", Toast.LENGTH_LONG).show();
            return;
        }
        if (null == BaseApplication.getIntance().getLoginBean()) {
            Toast.makeText(ObtainModeActivity.this, "没有登录信息", Toast.LENGTH_LONG).show();
            return;
        }

        if (null == BaseApplication.getIntance().getLoginBean().getCabinetId()) {
            Toast.makeText(ObtainModeActivity.this, "没有登录柜子信息", Toast.LENGTH_LONG).show();
            return;
        }


        if(add_layout.getVisibility()==View.VISIBLE){
            String[] ass = getResources().getStringArray(R.array.a_z_);
            numberSum+=ass[index];
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String ye = year + "";
            ye = ye.substring(2, 4);
            numberSum+=ye;
            numberSum+=mCompanySearchModel.getCompanynum();
            numberSum += company_info_save.getText().toString();

        }else{

            numberSum="";
        }





        if (add_layout1.getVisibility()!=View.VISIBLE) {

            numberSum1="";


        } else {

            String[] ass = getResources().getStringArray(R.array.a_z_);
            numberSum1+=ass[index1];
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String ye = year + "";
            ye = ye.substring(2, 4);
            numberSum1+=ye;
            numberSum1+=mCompanySearchModel.getCompanynum();
            numberSum1 += company_info_save1.getText().toString();
        }


        if (add_layout2.getVisibility()!=View.VISIBLE) {

            numberSum2="";


        } else {

            String[] ass = getResources().getStringArray(R.array.a_z_);
            numberSum2+=ass[index2];
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String ye = year + "";
            ye = ye.substring(2, 4);
            numberSum2+=ye;
            numberSum2+=mCompanySearchModel.getCompanynum();
            numberSum2 += company_info_save2.getText().toString();
        }


        if (add_layout3.getVisibility()!=View.VISIBLE) {

            numberSum3="";

        } else {

            String[] ass = getResources().getStringArray(R.array.a_z_);
            numberSum3+=ass[index3];
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String ye = year + "";
            ye = ye.substring(2, 4);
            numberSum3+=ye;
            numberSum3+=mCompanySearchModel.getCompanynum();
            numberSum3 += company_info_save3.getText().toString();
        }

        if (add_layout4.getVisibility()!=View.VISIBLE) {


            numberSum4="";

        } else {

            String[] ass = getResources().getStringArray(R.array.a_z_);
            numberSum4+=ass[index4];
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String ye = year + "";
            ye = ye.substring(2, 4);
            numberSum4+=ye;
            numberSum4+=mCompanySearchModel.getCompanynum();
            numberSum4 += company_info_save4.getText().toString();
        }

        if (add_layout5.getVisibility()!=View.VISIBLE) {

            numberSum5="";



        } else {

            String[] ass = getResources().getStringArray(R.array.a_z_);
            numberSum5+=ass[index5];
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            String ye = year + "";
            ye = ye.substring(2, 4);
            numberSum5+=ye;
            numberSum5+=mCompanySearchModel.getCompanynum();
            numberSum5+= company_info_save5.getText().toString();
        }

         List<String> list=new ArrayList<>();
        if(!TextUtils.isEmpty(numberSum)){
            list.add(numberSum);
        }
        if(!TextUtils.isEmpty(numberSum1)){
            list.add(numberSum1);
        }
        if(!TextUtils.isEmpty(numberSum2)){
            list.add(numberSum2);
        }
        if(!TextUtils.isEmpty(numberSum3)){
            list.add(numberSum3);
        }
        if(!TextUtils.isEmpty(numberSum4)){
            list.add(numberSum4);

        }if(!TextUtils.isEmpty(numberSum5)){
            list.add(numberSum5);


        }


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetId", BaseApplication.getIntance().getLoginBean().getCabinetId());
        map.put("companyId", mCompanySearchModel.getCompanyid());
//        map.put("gridType", cabType);
        map.put("phone", mCompanySearchModel.getContact());
        map.put("adminid", BaseApplication.getIntance().getLoginBean().getId());
        map.put("number",list );

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse>post(Urls.URL_OPENGRID)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse>(ObtainModeActivity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse> response) {

                       if(null!= response.body().msg){
                           Toast.makeText(ObtainModeActivity.this, response.body().msg, Toast.LENGTH_LONG).show();
                           Log.e("MainActivity", "onSuccess-----URL_OPENGRID---------------" + response.body().data);
                       }



                    }

                    @Override
                    public void onError(Response<LzyResponse> response) {

                        Log.e("MainActivity", "onError---------------------");
                        if(null!= response.body().msg){
                        Toast.makeText(ObtainModeActivity.this, response.body().msg, Toast.LENGTH_LONG).show();}
                    }
                });


    }




    private String preStatus="-1",curStatus="-1";

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
//            bundle.putString(CodeUtils.RESULT_STRING, result);
//            resultIntent.putExtras(bundle);
//            CaptureActivity.this.setResult(RESULT_OK, resultIntent);
//            CaptureActivity.this.finish();
            Toast.makeText(ObtainModeActivity.this, result, Toast.LENGTH_LONG).show();

//            curStatus=result;
//
//            if(!TextUtils.equals(curStatus,preStatus)){
//                preStatus=curStatus;
//
//                companySearchID(curStatus);
//            }

            companySearchID(result);

        }

        @Override
        public void onAnalyzeFailed() {
//            Intent resultIntent = new Intent();
//            Bundle bundle = new Bundle();
//            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
//            bundle.putString(CodeUtils.RESULT_STRING, "");
//            resultIntent.putExtras(bundle);
//            CaptureActivity.this.setResult(RESULT_OK, resultIntent);
//            CaptureActivity.this.finish();
            Toast.makeText(ObtainModeActivity.this, "没有识别到信息", Toast.LENGTH_LONG).show();
        }
    };


}
